'''
Created on 2020年3月3日
供应商管理
@author: Administrator
'''
import time, datetime

from flask import json

from common.public import *
from orm.model import Supplier, SupplierDetail, Service, ServiceDetail, db
from view.baseview import BaseView


class SupplierView(BaseView):
    def __init__(self):
        pass

    def list(self):
        """取得所有供应商列表，params：条件参数"""
        result=[]
        rows = Supplier.select().where(Supplier.status != SUPPLIER_STATUS_CANCLE).order_by(Supplier.createdate.desc())
        for row in rows:
                data = {
                    "id":row.id,
                    "name":row.name
                 }
                result.append(data )
                
        return super().resultSet(200, "", result)
    
    def query(self, params):
        """根据条件取得供应商列表，params：条件参数"""
        result=[]
        where_condition = True
        where_detail = True
        if params["keyword"]:
            likestr= "%"+params["keyword"] +"%"
            where_condition=(Supplier.name ** likestr )
            where_condition=where_condition | (Supplier.tel ** likestr )
            where_condition=where_condition | (Supplier.contacter ** likestr )
        if params["status"]:
            where_condition =where_condition &(Supplier.status.in_(params["status"]))
        if params["serviceid"]:
            where_detail =where_detail &(SupplierDetail.service.in_(params["serviceid"]))
        total = Supplier.select().where(where_condition).count()
        rows = Supplier.select().where(where_condition).order_by(Supplier.createdate.desc()).paginate(int(params["pageNo"]), int(params["pagesize"]))
        for row in rows:
            isfinded = False
            detail = []
            for drow in row.supplierdetail_set.where(where_detail):
                isfinded = True
                ddata = {
                    "id":drow.id,
                    "serviceid":drow.service.id,
                    "service":drow.service.name,
                    "supplierid":drow.supplier.id,
                    "supplier":drow.supplier.name,
                    "specs":drow.specs,
                    "cost":drow.cost,
                    "price":drow.price,
                    "area":drow.area,
                    "memo":drow.memo,
                    "industry":drow.industry
                 }
                detail.append(ddata )
            if isfinded:
                data = {
                    "id":row.id,
                    "name":row.name,
                    "tel":row.tel,
                    "contacter":row.contacter,
                    "city":row.city,
                    "poclear":row.poclear,
                    "paytype":row.paytype,
                   "createdate":str(row.createdate),
                   "isinvoice":row.isinvoice,
                   "status":row.status,
                   "remark":row.remark,
                   "detail":detail
                 }
                result.append(data )
            elif  not params["serviceid"]:
                data = {
                    "id":row.id,
                    "name":row.name,
                    "tel":row.tel,
                    "contacter":row.contacter,
                    "city":row.city,
                    "poclear":row.poclear,
                    "paytype":row.paytype,
                   "createdate":str(row.createdate),
                   "isinvoice":row.isinvoice,
                   "status":row.status,
                   "remark":row.remark,
                   "detail":detail
                 }
                result.append(data )
                
        return super().resultSet(200, "", result, total=total)
    
    @db.atomic()                   
    def add(self, params):
        """
        添加供应商
        """
        Supplier.create(
                    name=params["name"],
                    city=params["city"],
                    tel=params["tel"],
                    contacter=params["contacter"],
                    poclear = params["poclear"],
                    paytype = params["paytype"],
                    createdate=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                    isinvoice =params["isinvoice"],
                    remark =params["remark"],
                    status =params["status"]
                    )
        return super().resultSet(200, "添加成功", [])
        raise Exception("添加失败")         
    @db.atomic()                   
    def update(self, params):
        """
        更新供应商
        """
        rec= Supplier.get(Supplier.id==params["id"])
        rec.name=params["name"]
        rec.city=params["city"]
        rec.tel=params["tel"]
        rec.contacter=params["contacter"]
        rec.poclear=params["poclear"]
        rec.paytype=params["paytype"]
        rec.isinvoice=params["isinvoice"]
        rec.remark=params["remark"]
        rec.status=params["status"]
        rec.save()
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")
    @db.atomic()                   
    def addDetail(self, params):
        """
        添加供应商服务明细
        """
        SupplierDetail.create(
                    service=params["serviceid"],
                    supplier=params["supplierid"],
                    specs=params["specs"],
                    cost=params["cost"],
                    price = params["price"],
                    area = params["area"],
                    industry = params["industry"],
                    memo =params["memo"]
                    )
        return super().resultSet(200, "添加成功", [])
        raise Exception("添加失败")         
    @db.atomic()                   
    def updateDetail(self, params):
        """
        更新供应商服务明细
        """
        rec= SupplierDetail.get(SupplierDetail.id==params["id"])
        rec.service=params["serviceid"]
        rec.supplier=params["supplierid"]
        rec.specs=params["specs"]
        rec.cost=params["cost"]
        rec.price=params["price"]
        rec.area=params["area"]
        rec.industry=params["industry"]
        rec.memo=params["memo"]
        rec.save()
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")
    @db.atomic()                   
    def delete(self, params):
        """
        删除供应商
        """
        SupplierDetail.delete().where(SupplierDetail.supplier==params["id"]).execute()
        Supplier.delete().where(Supplier.id==params["id"]).execute()
        return super().resultSet(200, "删除成功", {})
        raise Exception("删除失败")
    
    @db.atomic()                   
    def deleteDetail(self, params):
        """
        删除供应商服务项目
        """
        SupplierDetail.delete().where(SupplierDetail.id==params["id"]).execute()
        return super().resultSet(200, "删除成功", {})
        raise Exception("删除失败")
    
    def getServices(self):
        """取得服务列表，params：条件参数"""
        result=[]
        rows = Service.select().order_by(Service.id)
        for row in rows:
            data = {
                "id":row.id,
                "name":row.name,
                "time":row.time,
                "unit":row.unit
             }
            result.append(data )
        return super().resultSet(200, "", result)
 
    def getServicesDetail(self, id):
        """取得服务明细，params：条件参数"""
        result=[]
        rows = ServiceDetail.select().where((ServiceDetail.service_id == id) & (ServiceDetail.isactive!=COMMON_FALSE)).order_by(ServiceDetail.id)
        for row in rows:
            data = {
                "id":row.id,
                "name":row.service.name,
                "spec":row.spec,
                "type":row.type,
                "unit":row.unit,
                "cost":row.cost,
                "price":row.price,
                "items":row.items,
                "countup":row.countup,
                "amountup":row.amountup,
                "number":row.number,
                "memo":row.memo
             }
            result.append(data)
        print(result)
        return super().resultSet(200, "", result)
   
